import CryptoJS from 'crypto-js'
import BigInt from 'big-integer'

const aesOffest = '0102030405060708'
const firstKey = '0CoJUm6Qyw8W8jud'
const pubKey = '010001'
const modulus = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7'

// 生成随机数(数字+字母)，size默认16
const createSecretKey = (size) => {
  const keys = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let key = ''
  for (let i = 0; i < size; i++) {
    let pos = Math.random() * keys.length
    pos = Math.floor(pos)
    key = key + keys.charAt(pos)
  }
  return key
}

// aes加密方法
const aesEncrypt = (word, _secKey, _aes) => {
  const key = CryptoJS.enc.Utf8.parse(_secKey) // 十六位十六进制数作为密钥
  const iv = CryptoJS.enc.Utf8.parse(_aes) // 十六位十六进制数作为密钥偏移量
  const srcs = CryptoJS.enc.Utf8.parse(word)
  const encrypted = CryptoJS.AES.encrypt(srcs, key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 })
  const res = encrypted.toString()
  return res
}

// 填充方法
const zfill = (str, size) => {
  while (str.length < size) { str = '0' + str }
  return str
}

// rsa加密方法
const rsaEncrypt = (word, _pubKey, _modulus) => {
  const _text = word.split('').reverse().join('')
  const biText = BigInt(CryptoJS.enc.Utf8.parse(_text).toString(), 16)
  const biEx = BigInt(_pubKey, 16)
  const biMod = BigInt(_modulus, 16)
  const biRet = biText.modPow(biEx, biMod)
  return zfill(biRet.toString(16), 256)
}

export const encryptFor163Weapi = (obj) => {
  const text = JSON.stringify(obj)
  const secKey = createSecretKey(16)
  const firstRes = aesEncrypt(text, firstKey, aesOffest) //  1次 aes
  const secondRes = aesEncrypt(firstRes, secKey, aesOffest) // 2次 aes
  const encSecKey = rsaEncrypt(secKey, pubKey, modulus) // 1次 rsa
  return {
    params: secondRes,
    encSecKey
  }
}
